<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录</title>
    <link rel="stylesheet" href="/filetrans/css/style.css">
</head>
<body>
<div th:if="${param.logout}" class="alert alert-success">
    您已成功退出系统
</div>
<div class="auth-container">
    <h1>登录</h1>
    <form th:action="@{/filetrans/auth/login}" method="post" onsubmit="return checkUser(event)">
        <div class="form-group">
            <label for="username">用户名</label>
            <input type="text" id="username" name="username" required>
        </div>
        <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" name="password" required>
        </div>
        <button type="submit">登录</button>
        <p>还没有账号？<a href="/filetrans/register">注册</a></p>
    </form>
</div>
</body>
<script src="/filetrans/js/md5.min.js"></script>
<script>
    async function checkUser(event) {
        // 阻止表单默认提交行为
        event.preventDefault();
        const username = document.getElementById('username').value;

        const passwordInput = document.getElementById('password');
        const password = md5(passwordInput.value);

        try {
            // 检查用户名是否存在
            const response = await fetch(`/filetrans/auth/check/${username}/${password}`);
            const data = await response.text(); // 假设后端返回纯文本

            if (data === '验证成功') {
                // 创建一个隐藏的密码字段（或直接替换原密码字段的值）
                const hiddenPassword = document.createElement('input');
                hiddenPassword.type = 'hidden';
                hiddenPassword.name = 'password';
                hiddenPassword.value = password;
                // 移除原始密码字段（防止明文传输）
                passwordInput.remove();
                // 将加密后的密码字段添加到表单
                event.target.appendChild(hiddenPassword);
                // 手动提交表单
                event.target.submit();
            } else {
                alert("用户名或密码错误！");
                return false;
            }
        } catch (error) {
            console.error('Error:', error);
            alert("校验失败! " + error.message);
        }
        // 返回 false 阻止表单默认提交
        return false;
    }
</script>
</script>
</html>